/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import {
  Controller,
  Post,
  Req,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Request } from 'express';
import { diskStorage } from 'multer';
import { extname } from 'path';
import { ResponseData, ResponseDataProps } from 'src/common/response.data';

@Controller('upload')
export class UploadController {
  @Post()
  @UseInterceptors(
    FileInterceptor('file', {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-call
      storage: diskStorage({
        destination: './uploads',
        filename: (req: Request, file: any, callback: any) => {
          const randomName: any = Array(32)
            .fill(null)
            .map(() => Math.round(Math.random() * 16).toString(16))
            .join('');
          // eslint-disable-next-line @typescript-eslint/no-unsafe-call
          callback(null, `${randomName}${extname(file.originalname)}`);
        },
      }),
      fileFilter: (req, file, callback) => {
        if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
          return callback(new Error('Only image files are allowed!'), false);
        }
        callback(null, true);
      },
      limits: {
        fileSize: 1024 * 1024 * 5, // 5MB
      },
    }),
  )
  uploadImage(
    @UploadedFile() file: Express.Multer.File,
    @Req() req: Request,
  ): ResponseDataProps {
    const staticPath = `${req.protocol}://${req.get('host')}/${file.path}`;
    // const targetObj: any = {
    //   filename: file.filename,
    //   originalname: file.originalname,
    //   size: file.size,
    //   mimetype: file.mimetype,
    //   path: staticPath,
    // };
    // console.log(targetObj);
    // console.log(' staticPath == ', staticPath);
    return ResponseData.success(staticPath);
  }
}
